<?php
/**
 * 房源管理
 */
namespace Member\Controller;
use Org\Yike\Member;
class UsedController extends CommonController {
    public function _initialize(){
        parent::_initialize();
        $this->is_login();
        $this->status = getStatus('used');
        $this->menu = getLinkMenuFor(array(2,8,10,17,20,21,22,23,24),1);
    }
    //自己房源列表
    public function index(){
        $sell = I ('get.sell', 0)? I ('get.sell', ''): 0;
        $member = new Member();
        $map = array (
            'u.status' => array ('neq',4)
        );
       switch ($sell){
           case 0:
               break;
           case 1:
               $map['u.sell_type'] = $sell;
               break;
           case 2:
               $map['u.sell_type'] = $sell;
               break;
           case 3:
               $map['u.sell_type'] = $sell;
               break;
           case 4:
               $map['u.user_id'] = $this->user['id'];
               $map['u.owner'] = 1;
               break;
           case 5:
               $map['u.keyer'] = $this->user['id'];
               break;
           case 6:
               $map['u.maintain'] = $this->user['id'];
               break;
           case 7:
               $map['u.prospect'] = $this->user['id'];
               break;
       }
        //var_dump($map);die;
        $list = $member::newgetUsedList(20,$map,true);
        $on[$sell] = 'on';
        $this->list = $list;
        $this->assign ('on',$on);
        $this->display();
    }
    //其他房源列表
   /* public function other (){
        $member = new Member();
        $map = array (
            'u.user_id<>'.$this->user['id'],
            'u.status<>4'
        );
        $list = $member::newgetUsedList(20,$map,true);
        $this->list = $list;
        $this->display();
    }*/

    public function add(){
        //如果是经纪人发布房源必先完善个人信息
        $spoce = M ('user_info')->field ('id,group,cate_id')->where (array ('user_id'=>session(userInfo)['id']))->find ();
        if ($spoce['cate_id'] > 1 && empty ($spoce['group'])){
            $this->error('个人信息审核中......');
        }
        if(IS_POST){
            $data = $_POST['data'];
            //房源是否已存在
            $map = array (
                'dict_id' => $_POST['room']['rid']
            );
            $is_exist = M ('used')->field ('id')->where ($map)->find ();
            if ($is_exist){
                $this->error('房源已存在',U ('Used/index'));
            }
            $data['dict_id'] = $_POST['room']['rid'];
            $data['area'] = $_POST['room']['area'];
            $data['map'] = $_POST['estate']['map'];
            $data['address'] = $_POST['estate']['address'];
            $data['area_id'] = $_POST['estate']['area_id'];
            $data['years'] = $_POST['estate']['years'];
            $data['mating'] = $_POST['mating'];
            $data['metro'] = intval($_POST['metro']);
            //计算层据在位置
            $total = M ('build')->where ("bid={$_POST['build']['bid']}")->getField('height');
            $data['floor'] = scope($total, $_POST['room']['floor']);
            $data['floor_alias'] = $_POST['room']['floor'].'/'.$total;

            $info = strip_tags($data['info']);
            $content = stripslashes($info);
            $data['info'] = addslashes(msubstr(str_replace(array("'","\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;','&nbsp;'), '', strip_tags($content)),0,1000,'utf-8',false));
            $data['user_id'] = $this->user['id'];
            $data['add_time']  = date ('Y-m-d H:i:s');
            $mating = empty (I ('post.mating', ''))? array (): I ('post.mating', '');
            $data['mating'] = implode(',', $mating);
            $data['decorate'] = intval($_POST['decorate']);
            $data['chamber'] = $_POST['chamber'];
            $data['hall'] = $_POST['hall'];
            $data['kitchen'] = $_POST['kitchen'];
            $data['toilet'] = $_POST['toilet'];
            $data['balcony'] = $_POST['balcony'];
            $data['aspect'] = intval($_POST['room']['aspect']);
            $data = $this->_insertPic($data);
            //如果有上传图片
            if (!empty ($data['file'])){
                $data['prospect'] = $this->user['id'];
            }
            //获取小区名字
            $data['estate_id'] = $_POST['estate']['id'];
            $e_name = M ('estate')->where (array ('id'=>$data['estate_id']))->getField('title');
            $data['estate'] = $e_name;
            //判断是否已存在房源
            $is_room = M ('used')->where ('dict_id='.$data['dict_id'])->getField('id');
            if ($is_room) $this->error ('房源已存在');

            M('used')->create($data);
            if(M('used')->add($data)){
                $this->success('录入成功',U ('Used/index'));
            }else{
                $this->error('房源录入失败');
            }
        }else{
            $this->display();
        }
    }
    //第一步
   /* public function first (){
        $eid = I ('post.estate_id');
        $estate = I ('post.estate');
        $title = I ('post.title');
        if (empty($eid) || !M ('room')->where ("estate_id={$eid} and status=1")->count ()){
            //提示数据字典是否建好
           $this->error ('没有 "'.$title.'" 这个小区或者没有建相关字典，将跳转到手动输入',U ('Used/manual',array ('title'=>$title,'eid'=>$eid)),3);
        }
        $builds = M ('build')->where ("estate_id={$eid} and status=1")->select ();
        $this->assign ('eid',$eid);
        $this->assign ('builds',$builds);
        $this->assign ('estate', $estate);
        $this->assign ('title', $title);
        $this->display ();
    }*/
    //第二步
    public function second (){
        $data = I ('post.data');
        $data['unit'] = empty ($data['unit'])? 1: $data['unit'];
        $build = M ('build')->field ('bid,build,alias,height,estate_id')->where ("bid={$data['build']}")->find ();
        $unit = M ('unit')->field ('unid,unit,alias')->where ("unid={$data['unit']}")->find ();
        $room = M ('room')->field ('rid,room,alias,floor,area,aspect,chamber,hall,kitchen,toilet,balcony,img,f_alias')->where ("rid={$data['room']}")->find ();
        //小区信息
        $estate = M ('estate')->field ('id,title,address,years,map,area_id')->where ("id={$build['estate_id']}")->find ();
        $house_type = M ('used_type')->where ('status=1')->select ();
        //单元数
        $unit_count = M ('unit')->where (array ('build'=>$data['build']))->count ();
        //录入人所在分组人员
        $groups = M ('user_info')->field ('g.users')
            ->table (array ('yk_user_info'=>'u'))
            ->join('yk_division g on u.group=g.id','LEFT')
            ->where ('u.user_id='.$this->user['id'])
            ->find ();
        $users = M ('User')->field ('id,username')->where (array ('id'=>array ('in',trim($groups['users'],','))))-> select ();
        foreach ($users as &$val){
            if ($this->user['id'] == $val['id']){
                $val['sele'] = 'selected';
            }
        }


        $this->assign ('sell_type', $data['sell_type']);
        $this->assign ('users', $users);
        $this->assign ('unit_count',$unit_count);
        $this->assign ('estate', $estate);
        $this->assign ('house_type', $house_type);
        $this->assign ('build', $build);
        $this->assign ('unit', $unit);
        $this->assign ('room', $room);
        $this->assign ('user', $this->user);
        $this->assign ('title', I ('post.title'));
        $this->display ();
    }

    public function edit(){
        if(IS_POST){
            $id = intval($_POST['id']);
            //保存原来的数据
            $original = M ('used')
                ->field('title,mating,total_price,dict_id,years,map,address,sell_type,contacts,phone,phone1,phone2,phone3,purpose,property,encoded,chamber,hall,kitchen,toilet,aspect,decorate,area,keyer,keyno,prospect,maintain,balcony')
                ->where ('id='.$id)
                ->find ();
            $data = $_POST['data'];
            $data['mating'] = $_POST['mating'];
            $data['metro'] = intval($_POST['metro']);
            $info = strip_tags($data['info']);
            if(empty($data['title'])){
                $this->error('请填写房源名称');
            }
            $content = stripslashes($info);
            $data['info'] = msubstr(str_replace(array("'","\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;','&nbsp;'), '', strip_tags($content)),0,200);
            $data['info'] = addslashes($data['info']);
            $data['info'] = preg_replace('/<a[^>]*>|<\/a>/isU','',$data['info']);
            $data['mating'] = !empty($data['mating']) ? ','.implode(',',$data['mating']).',' : '';
            $room = $_POST['room'];
            $data['area'] = $room['area'];
            $data['aspect'] = $room['aspect'];
            $data['chamber'] = $_POST['chamber'];
            $data['hall'] = $_POST['hall'];
            $data['kitchen'] = $_POST['kitchen'];
            $data['toilet'] = $_POST['toilet'];
            $data['balcony'] = $_POST['balcony'];
            $data = $this->_insertPic($data);
            $msg = '';
            //如果有上传图片
            if (!empty ($data['file'])){
                $data['prospect'] = $this->user['id'];
                $msg .= '修改了户型图片';
                //发送信息给上一个实勘人

            }

            if(M('used')->where(array('id'=>$id,'user_id'=>$this->user['id']))->save($data)){
                //经纪人修改了房源跟进表记录修改内容
                $diff = array_diff_assoc($original, $data);
                foreach ($diff as $item=>$val){
                    if ($item == 'title') $msg .= '修改了房源名称,';
                    if ($item == 'area') $msg .= '修改了房源面积,';
                    if ($item == 'dict_id') $msg .= '修改了房源字典,';
                    if ($item == 'mating') $msg .= '修改了房屋配套,';
                    if ($item == 'decorate') $msg .= '修改了装修类型,';
                    if ($item == 'aspect') $msg .= '修改了房源朝向,';
                    if ($item == 'total_price') $msg .= '修改了房源总价,';
                    if ($item == 'chamber') $msg .= '修改了楼盘室,';
                    if ($item == 'hall') $msg .= '修改了楼盘厅,';
                    if ($item == 'kitchen') $msg .= '修改了楼盘厨,';
                    if ($item == 'toilet') $msg .= '修改了楼盘卫,';
                    if ($item == 'encoded') $msg .= '修改了房源编码,';
                    if (!empty ($data['phone']) && $item == 'phone') $msg .= '修改了业主手机号,';
                    if (!empty ($data['phone1']) && $item == 'phone1') $msg .= '修改了业主手机号,';
                    if (!empty ($data['phone2']) && $item == 'phone2') $msg .= '修改了业主手机号,';
                    if (!empty ($data['phone3']) && $item == 'phone3') $msg .= '修改了业主手机号,';
                    if ($item == 'contacts') $msg .= '修改了业主姓名,';
                    if ($item == 'sell_type') $msg .= '修改了房源属性,';
                    if ($item == 'address') $msg .= '修改了房源地址,';
                    if ($item == 'map') $msg .= '修改了楼盘地图,';
                    if ($item == 'years') $msg .= '修改了楼盘年代,';
                    if ($item == 'property') $msg .= '修改了楼盘产权,';//keyer,keyno,prospect,maintain
                    if ($item == 'purpose') $msg .= '修改了楼盘产权,';
                    if ($item == 'keyer') $msg .= '修改了钥匙人,';
                    if ($item == 'keyno') $msg .= '修改了钥匙编号,';
                    if ($item == 'balcony') $msg .= '修改了阳台,';
                    if ($item == 'keyno') $msg .= '修改了钥匙编号,';
                }
                $msg = empty ($msg)? '什么也没修改': $msg;
                $follow = array (
                    'user_id' => $this->user['id'],
                    'source_id' => $id,
                    'uname' => $this->user['username'],
                    'discuss' => $msg,
                    'add_time' => time ()
                );
                $res = M ('follow')->add ($follow);

                $this->success('编辑成功', U('used/index'));
            }else{

                $this->error('编辑失败');
            }
        }else{
            $id = I ('get.id');
            $info = M('used')->where('id='.$id.' and status<>4')->find();
            if(!$info){
                $this->error('找不到对应的房源信息');
            }
            //字典信息
            $dict = M ('room as r')->field ('r.*,b.bid,b.alias as balias,u.unid,u.alias as ualias')
                ->join ('yk_unit u on r.unit=u.unid','LEFT')
                ->join ('yk_build b on r.build=b.bid', 'LEFT')
                ->where ('rid='.$info['dict_id'])
                ->find ();
            //单元总数
            $unit_count = M ('unit')->where ('build='.$dict['bid'])->count ();
            $files = json_decode($info['file']);
            $mating = explode(',', $info['mating']);
            $info['mating'] = $mating;
            $info['files'] = $files;
            //录入人所在分组人员
            $groups = M ('user_info')->field ('g.users')
                ->table (array ('yk_user_info'=>'u'))
                ->join('yk_division g on u.group=g.id','LEFT')
                ->where ('u.user_id='.$this->user['id'])
                ->find ();
            $users = M ('User')->field ('id,username')->where (array ('id'=>array ('in',trim($groups['users'],','))))-> select ();
            //维护人
            $maintain = M ('user')->where ('id='.$info['maintain'])->getField('username');
            foreach ($users as &$val){
                if ($info['keyer'] == $val['id']){
                    $val['key_sele'] = 'selected';
                }
                if ($info['maintain'] == $val['id']){
                    $val['ma_sele'] = 'selected';
                }
            }
            //跟进信息
            $follows = M ('follow')->where (array ('source_id'=>$id,'type'=>array ('neq',2)))->order ('type asc,add_time desc')->select ();
            //跟进信息分类
            $m_follows = [];
            $a_follows = [];
            foreach ($follows as $v){
                if ($v['deed'] == 2){
                    $m_follows[] = $v;
                }else{
                    $a_follows[] = $v;
                }
            }

            $this->assign ('m_follows', $m_follows);
            $this->assign ('a_follows', $a_follows);
            $this->assign ('maintain', $maintain);
            $this->assign ('users', $users);
            $this->assign ('unit_count', $unit_count);
            $this->assign('info',$info);
            $this->assign('dict',$dict);
            $this->seoKey(array('seo_title'=>'编辑房源'));
            $this->display();
        }
    }
    //跟进房源
    public function follow (){
        if (IS_GET){
            $house_id = I ('get.id', '');
            $house = D ('used')->where ('id='.$house_id)->find ();
            $follows = M ('follow')->where (array ('source_id'=>$house_id))->order ('add_time desc')->select ();
            //字典信息
            $dict = M ('room as r')->field ('r.*,b.bid,b.alias as balias,u.unid,u.alias as ualias')
                ->join ('yk_unit u on r.unit=u.unid','LEFT')
                ->join ('yk_build b on r.build=b.bid', 'LEFT')
                ->where ('rid='.$house['dict_id'])
                ->find ();
            //判断是否有权限查看业主信息
            $user_id = session('userInfo.id');
            $view_auth = true;
            if ($house['owner']==2 || $user_id != $house['user_id'] && $house['status']==1){
                $view_auth = false;
            }
            $mating = explode(',', $house['mating']);
            $house['mating'] = $mating;
            $this->assign ('follows', $follows);
            $this->assign ('info', $house);
            $this->assign('dict',$dict);
            $this->display ('do_follow');
        }elseif(IS_POST){
            $user_id = I ('post.user_id', '');
            $used_id = I ('post.used_id', '');
            $conter = I ('post.conter', '');
            $uname = M ('user')->where (array ('id'=>$user_id))->getField('username');
            $today = date ('Y-m-d');
            $starTime = strtotime ($today." 00:00:00");
            $endTime = strtotime ($today." 23:59:59");
            $follow  = M ('follow')
                ->where (array ('user_id'=>$user_id,'type'=>3,'status'=>-1,'source_id'=>$used_id))
                ->find ();
            if (empty ($follow)){
                $data = array (
                    'user_id' => $user_id,
                    'source_id' => $used_id,
                    'type' => 1,
                    'discuss' => $conter,
                    'uname' => $uname,
                    'deed' => 2,
                    'add_time' => time()

                );
                $res = M ('follow')->add($data);
            }else{
                $where = 'user_id='.$user_id.' and type=3 and status=-1 and source_id='.$used_id;
                $sql = 'update yk_follow set discuss=concat(discuss,",'.$conter.'"),status=1 where '.$where;
                $res = M ('Follow')->execute($sql);
            }
            if ($res){
                exit ('ok');
            }else{
                exit ('fail');
            }
        }else{
            $member = new Member();
            $list = $member::getFollow(20,'ou.user_id='.$this->user['id'],true);


            $this->assign ('list', $list);
            $this->display ();
        }

    }

    public function message(){
        $member = new Member();
        $list = $member::getUsedMess(20,'ou.user_id='.$this->user['id'],true);
        $this->list = $list;
        $this->type = order_type('used');
        $this->seoKey(array('seo_title'=>'房源跟进留言'));
        $this->display();
    }

    //留言详细
    public function editMess(){
        $id = intval($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
        $order = M('order_used')->where(array('id'=>$id,'store_id='=>$this->user['id']))->find();
        if(!$order['id']){
            $this->error('找不到对应的房源信息');
        }
        if($_POST){
            $data = array('info'=>strip_tags($_POST['info']),'status'=>intval($_POST['status']));
            $res = M('order_used')->where(array('id'=>$id,'store_id='=>$this->user['id']))->save($data);
            if($res){
                $this->success("留言保存成功");
            }else{
                $this->error("留言保存失败");
            }

        }else{
            $this->used = M('used')->where(array('id'=>$order['used_id']))->field('title')->find();
            $this->order = $order;
            $this->seoKey(array('seo_title'=>'二手房源留言详细'));
            $this->display();
        }
    }

    public function del(){
        $info = M('used')->where(array('id'=>intval($_GET['id'])))->find();
        if(!$info){
            $this->error('找不到对应的房源信息');
        }
        if(M('used')->where(array('id'=>$info['id']))->save(array('status'=>4))){
            $this->success('房源删除成功!',U('index'));
        }else{
            $this->error('房源删除失败');
        }
    }
    //匹配房源字典
    public function ajaxMach (){
        $title = I ('get.title', '');
        $map['title'] = array('like', '%'.$title.'%');
        $map['_logic'] = 'OR';
        $map['alias'] = array('like', '%'.$title.'%');
        $data = M ('estate')->field('id,title')->where($map)->select();
        if (empty ($data)){
            exit (json_encode (array ('state'=>'fail','data'=>'')));
        }
        exit (json_encode(array ('state'=>'ok','data'=>$data)));
    }
    //获取字典
    public function ajaxDict (){
        $eid = I ('get.eid', '');
        $field = 'es.id as eid,es.title as ename,es.years,es.map,es.build,es.unit,es.floor,es.room,es.address,ca.id as cid,ca.name as cname';
        $map = array (
            'es.id'=>$eid,
            'es.area_id=ca.id',
        ) ;
        $res = M ('estate')->table (array ('yk_area_cate'=>'ca','yk_estate'=>'es'))
            ->field ($field)
            ->where ($map)
            ->find ();
        if (empty ($res)){
            exit (json_encode (array ('state'=>'fail','data'=>'')));
        }
        exit (json_encode (array ('state'=>'ok','data'=>$res)));
    }
    public function getDict (){
        $build = I ('get.build', '');
        $unit = I ('get.unit', '');
        $floor = I ('get.floor', '');
        $room = I ('get.room', '');
        $eid = I ('get.eid', '');
        $map = array ('estate_id'=>$eid,'build'=>$build,'unit'=>$unit,'fool'=>$floor,'room'=>$room);
        $res = M ('dict')->where ($map)->find();
        if (empty ($res)){
            exit (json_encode (array ('state'=>'fail','data'=>'')));
        }
        exit (json_encode (array ('state'=>'ok','data'=>$res)));
    }
    //房源检索
    public function retrieve (){
        if (IS_POST){
            $member = new Member();
            $data = I ('post.', '');
            $list = $member::retrieve($data,true);
            $this->assign ('list', $list);
            $this->display ('list');
        }else{
            //获取所户型
            $house_type = M ('used_type')->select ();
            $this->assign ('type', $house_type);
            $this->display ();
        }
    }
    //手动建立房源
    public function  manual(){
        if (IS_POST){
            $used = I ('post.data');
            $used = $this->_insertPic($used);
            $used['estate_id'] = empty ($used['estate_id'])? '':  $used['estate_id'];
            //楼栋表
            $build = I ('post.build');
            $build['estate_id'] = $used['estate_id'];
            $build['add_time'] = date ('Y-m-d H:i:s');
            $build['alias'] = empty ($build['alias'])?$build['build'].'栋':$build['alias'];
            $build['status'] = 2;
            $bid = M ('build')-> add ($build);
            //单元表
            $unit = I  ('post.unit');
            $unit['estate_id'] = $used['estate_id'];
            $unit['alias'] = empty ($unit['alias'])?$unit['unit']:$unit['alias'];
            $unit['build'] = $bid;
            $unit['status'] = 2;
            $unit['add_time'] = date ('Y-m-d H:i:s');
            $unid = M ('unit')->add ($unit);
            //房间表
            $room = I ('post.room');
            $room['floor'] = $used['floor'];
            $room['alias'] = empty ($room['alias'])?$room['unit']:$room['alias'];
            $room['estate_id'] = $room['estate_id'];
            $room['build'] = $bid;
            $room['unit'] = $unid;
            $room['chamber'] = $used['chamber'];
            $room['hall'] = $used['hall'];
            $room['kitchen'] = $used['kitchen'];
            $room['toilet'] = $used['toilet'];
            $room['img'] = $used['img'];
            $room['status'] = 2;
            $room['add_time'] = date ('Y-m-d H:i:s');
            $rid = M  ('room')->add ($room);
            //房源表
            $used['dict'] = $rid;
            $used['decorate'] = $room['decorate'];
            $used['aspect'] = $room['aspect'];
            //计算层据在位置
            $used['floor'] = scope($build['height'], $room['floor']);
            $used['floor_alias'] = $used['floor'].'/'.$build['height'];
            $mating = empty (I ('post.mating', ''))? array (): I ('post.mating', '');
            $used['mating'] = implode(',', $mating);
            $used['area'] = $room['area'];
            $used['user_id'] = session(userInfo)['id'];
            $U = M ('used')->add ($used);
            if($U){
                $this->success('录入成功',U ('Used/index'));
            }else{
                $this->error('房源录入失败');
            }
        }else{
            //录入人所在分组人员
            $groups = M ('user_info')->field ('g.users')
                ->table (array ('yk_user_info'=>'u'))
                ->join('yk_division g on u.group=g.id','LEFT')
                ->where ('u.user_id='.$this->user['id'])
                ->find ();
            $users = M ('User')->field ('id,username')->where (array ('id'=>array ('in',trim($groups['users'],','))))-> select ();
            foreach ($users as &$val){
                if ($this->user['id'] == $val['id']){
                    $val['sele'] = 'selected';
                }
            }



            $this->assign ('users', $users);
            $title = I ('get.title', '');
            $eid = I ('get.eid', '');
            $this->assign ('eid', $eid);
            $this->assign ('title',$title);
            $this->display ();
        }
    }

}

